package com.easylinkin.linkappapi.machinery.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.machinery.service.ElevatorWorkRecordService;
import com.easylinkin.linkappapi.machinery.vo.ElevatorWorkStatisticsVO;
import com.easylinkin.linkappapi.machinery.vo.ExportWorkStatisticsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 升降机工作循环记录
 *
 * @author Xiaoyang
 * @since 2022-09-19
 */
@RestController
@RequestMapping("/machinery/elevatorWorkRecord")
@Api(tags = "升降机工作循环记录管理")
public class ElevatorWorkRecordController {

  @Autowired
  private ElevatorWorkRecordService elevatorWorkRecordService;

  @Autowired
  private DeviceService deviceService;

  /**
   * 群升降机工作循环统计查询
   * @param statisticsVO
   * @return
   */
  @PostMapping("getStatisticsOrderByMachinery")
  @ApiOperation("根据条件，群升降机工作循环统计查询不分页查询")
  public RestMessage getStatisticsOrderByMachinery(@RequestBody ElevatorWorkStatisticsVO statisticsVO){
    return RestBuilders.successBuilder().data(elevatorWorkRecordService.getStatisticsOrderByMachinery(statisticsVO)).build();
  }

  /**
   * 获取指定时间指定设备的运行记录统计
   * @param requestModel
   * @return
   */
  @PostMapping("getStatisticsDetailByMachinery")
  @ApiOperation("获取指定时间指定设备的运行记录统计")
  public RestMessage getStatisticsDetailByMachinery(@RequestBody RequestModel<ElevatorWorkStatisticsVO> requestModel){
    Assert.notNull(requestModel, "参数不能为空");
    Assert.notNull(requestModel.getCustomQueryParams(), "参数不能为空");
    Assert.notNull(requestModel.getPage(), "分页参数不能为空");
    Assert.notNull(requestModel.getPage().getCurrent(), "当前页不能为空");
    Assert.notNull(requestModel.getPage().getSize(), "当前页码条数不能为空");
    Assert.notNull(requestModel.getCustomQueryParams().getCode(), "设备code不能为空");
    Assert.notNull(requestModel.getCustomQueryParams().getStartTime(), "开始时间不能为空");
    Assert.notNull(requestModel.getCustomQueryParams().getEndTime(), "结束时间不能为空");
    return RestBuilders.successBuilder().data(elevatorWorkRecordService.getStatisticsDetailByMachinery(requestModel)).build();
  }

  /**
   * 根据条件，导出升降机工作循环统计列表
   */
  @PostMapping("export")
  @ApiOperation("导出升降机详情报表")
//  @CommonOperateLogAnnotate(module = LogConstant.LogModule.LABOR_MANAGEMENT, desc = "导出花名册")
  public void export(@RequestBody RequestModel<ElevatorWorkStatisticsVO> requestModel, HttpServletRequest request, HttpServletResponse response) {
    requestModel.getPage().setSize(-1);
    ElevatorWorkStatisticsVO areaDTO = requestModel.getCustomQueryParams();
    String code = areaDTO.getCode();
    Assert.notNull(code, "设备编号 不能为空");
    Assert.notNull(areaDTO.getStartTime(), "开始时间 不能为空");
    Assert.notNull(areaDTO.getEndTime(), "结束时间 不能为空");

    Page<ElevatorWorkStatisticsVO> iPage = elevatorWorkRecordService.getStatisticsDetailByMachinery(requestModel);
    List<ExportWorkStatisticsVO> list = new ArrayList<>();
    iPage.getRecords().forEach(r ->{
      ExportWorkStatisticsVO vo = new ExportWorkStatisticsVO();
      vo.setRefDate(r.getRefDate());
      vo.setTotalPeriod(r.getTotalPeriod());
      vo.setWorkCount(r.getWorkCount());
      List<ElevatorWorkStatisticsVO> hourList = r.getHourList();
      if (CollectionUtil.isNotEmpty(hourList)){
        Map<String, List<ElevatorWorkStatisticsVO>> collect =
                hourList.stream().collect(Collectors.groupingBy(ElevatorWorkStatisticsVO::getHour));
        vo.setZeroData(collect.get("00").get(0).getWorkCount().toString());
        vo.setOneData(collect.get("01").get(0).getWorkCount().toString());
        vo.setTwoData(collect.get("02").get(0).getWorkCount().toString());
        vo.setThreeData(collect.get("03").get(0).getWorkCount().toString());
        vo.setFourData(collect.get("04").get(0).getWorkCount().toString());
        vo.setFiveData(collect.get("05").get(0).getWorkCount().toString());
        vo.setSixData(collect.get("06").get(0).getWorkCount().toString());
        vo.setSevenData(collect.get("07").get(0).getWorkCount().toString());
        vo.setEightData(collect.get("08").get(0).getWorkCount().toString());
        vo.setNineData(collect.get("09").get(0).getWorkCount().toString());
        vo.setTenData(collect.get("10").get(0).getWorkCount().toString());
        vo.setElevenData(collect.get("11").get(0).getWorkCount().toString());
        vo.setTwelveData(collect.get("12").get(0).getWorkCount().toString());
        vo.setThirteenData(collect.get("13").get(0).getWorkCount().toString());
        vo.setFourteenData(collect.get("14").get(0).getWorkCount().toString());
        vo.setFifteenData(collect.get("15").get(0).getWorkCount().toString());
        vo.setSixteenData(collect.get("16").get(0).getWorkCount().toString());
        vo.setSeventeenData(collect.get("17").get(0).getWorkCount().toString());
        vo.setEighteenData(collect.get("18").get(0).getWorkCount().toString());
        vo.setNineteenData(collect.get("19").get(0).getWorkCount().toString());
        vo.setTwentyData(collect.get("20").get(0).getWorkCount().toString());
        vo.setTwentyOneData(collect.get("21").get(0).getWorkCount().toString());
        vo.setTwentyTwoData(collect.get("22").get(0).getWorkCount().toString());
        vo.setTwentyThreeData(collect.get("23").get(0).getWorkCount().toString());
      }
      list.add(vo);
    });
    //获取类型
    String keyValue = "日期:refDate,00:00-01:00:zeroData,01:00-02:00:oneData,02:00-03:00:twoData,03:00-04:00:threeData,04:00-05:00:fourData,05:00-06:00:fiveData," +
            "06:00-07:00:sixData,07:00-08:00:sevenData,08:00-09:00:eightData,09:00-10:00:nineData,10:00-11:00:tenData,11:00-12:00:elevenData,12:00-13:00:twelveData," +
            "13:00-14:00:thirteenData,14:00-15:00:fourteenData,15:00-16:00:fifteenData,16:00-17:00:sixteenData,17:00-18:00:seventeenData,18:00-19:00:eighteenData," +
            "19:00-20:00:nineteenData,20:00-21:00:twentyData,21:00-22:00:twentyOneData,22:00-23:00:twentyTwoData,23:00-24:00:twentyThreeData," +
            "总运行次数:workCount,总运行时长:totalPeriod" ;
    //设备名称（设备编号）运行次数报表
    Device device = deviceService.findOneByDeviceCode(code);
    String title = device.getName()+"("+device.getCode()+")运行次数报表";
    String fileName = title + ".xls";
    try {
      OutputStream outputStream = OutputStreamUtil
              .getOutputStream(request, response, fileName);
      ExcelTools.exportExcel(outputStream, keyValue, list, ExcelConstant.XLS, title);
      response.flushBuffer();
      outputStream.close();
    } catch (IOException e) {
      throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
    } catch (Exception e) {
      throw new RuntimeException("excel导出失败！" + e.getMessage());
    }
  }

  /**
   * 获取升降机的设备
   * @return
   */
  @GetMapping("getElevatorDevice")
  public RestMessage getElevatorDevice(){
    return RestBuilders.successBuilder().data(elevatorWorkRecordService.getElevatorDevice()).build();
  }

  /**
   * 今日升降机工效
   * @param statisticsVO
   * @return
   */
  @PostMapping("todayStatistics")
  @ApiOperation("今日升降机工效")
  public RestMessage todayStatistics(@RequestBody ElevatorWorkStatisticsVO statisticsVO){
    statisticsVO.setStartTime(DateUtil.getYYYYMMDDHHMMSSDate(DateUtil.getCurrentDayMixDate()));
    statisticsVO.setEndTime(DateUtil.getYYYYMMDDHHMMSSDate(DateUtil.getCurrentDayMaxDate()));
    return RestBuilders.successBuilder().data(elevatorWorkRecordService.getStatisticsSum(statisticsVO)).build();
  }

  /**
   * 升降机排行榜
   * @param statisticsVO
   * @return
   */
  @PostMapping("getStatisticsOrderByMachineryTop")
  @ApiOperation("吊装排行榜")
  public RestMessage getStatisticsOrderByMachineryTop(@RequestBody ElevatorWorkStatisticsVO statisticsVO){
    return RestBuilders.successBuilder().data(elevatorWorkRecordService.getStatisticsOrderByMachineryTop(statisticsVO)).build();
  }
  
}
